package mylab.io.base.model;


import cn.hutool.core.util.ArrayUtil;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import mylab.base.foundation.template.pojo.BaseStringIDPojo;
import mylab.utils.common.UuidUtil;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;

@Getter
@Setter
@ToString
public class BaseMsg extends BaseStringIDPojo implements Msg {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    protected LocalDateTime time = LocalDateTime.now();
    protected MsgType type = MsgType.Undefined;
    protected Terminal from;
    protected Terminal to;
    protected String code;
    @JsonIgnore
    protected byte[] payload;

    public BaseMsg() {
        this(UuidUtil.UU16());
    }

    public BaseMsg(String id) {
        this.id = id;
    }


    public String getPayloadString() {
        if (ArrayUtil.isEmpty(getPayload())) {
            return null;
        } else {
            return new String(getPayload(), StandardCharsets.UTF_8);
        }
    }

    public void setPayloadString(String payloadString) {
        setPayload(payloadString == null ? null : payloadString.getBytes(StandardCharsets.UTF_8));
    }
}
